import pygame
from pygame.locals import *
import time
import random


class moveing():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move_left_righe(self, speed=5):
        '''左右移动，默认是向右移动'''
        self.x += speed
        if self.x <= 0:
            self.x = 0
        elif self.x >= 406:
            self.x = 406

    def move_up_down(self, speed=-5):
        '''上下移动，默认是向上移动'''
        self.y += speed
        if self.y <= -20 or self.y >= 568:
            return True


class HeroPlane(moveing):
    '''玩家飞机（英雄）'''

    def __init__(self, screen_temp):
        self.x = 200
        self.y = 400
        moveing.__init__(self, self.x, self.y)

        self.screen = screen_temp
        self.image = pygame.image.load("./images/me.png")
        self.bullet_list = []  # 用于存放玩家子弹列表

    def display(self):
        '''绘制玩家飞机'''
        self.screen.blit(self.image, (self.x, self.y))

        # 绘制子弹
        for b in self.bullet_list:
            b.display()
            if b.move_up_down(-10):
                self.bullet_list.remove(b)

    def fire(self):
        self.bullet_list.append(Bullet(self.screen, self.x + 53, self.y))


class EnemyPlane(moveing):
    '''敌人飞机'''

    def __init__(self, screen_temp):
        self.x = random.choice(range(408))
        self.y = -75
        self.time = 50  # 从50开始
        self.bomb = 0  # 初始化为0，开始爆炸为1，爆炸结束为2
        self.bomb_num = 0  # 爆炸图片序号
        moveing.__init__(self, self.x, self.y)

        self.screen = screen_temp
        self.image = pygame.image.load("./images/e" + str(random.choice(range(3))) + ".png")
        self.bullet_list = []  # 用于存放敌机子弹列表

    def display(self):
        if self.bomb == 0:
            '''绘制敌人飞机'''
            self.screen.blit(self.image, (self.x, self.y))
            self.time += 1
        elif self.bomb == 1:
            image = pygame.image.load("./images/bomb" + str(self.bomb_num) + ".png")
            self.screen.blit(image, (self.x, self.y))
            self.bomb_num += 1
            # 爆炸完成
            if self.bomb_num == 4:
                self.bomb = 2

    def move(self, hero):
        self.y += 4
        if self.y >= 568:
            self.bomb = 2

        for bo in hero.bullet_list:
            if bo.x > self.x + 10 and bo.x < self.x + 92 and bo.y > self.y + 20 and bo.y < self.y + 60:
                hero.bullet_list.remove(bo)
                self.bomb = 1
                break


class Bullet(moveing):
    '''子弹类'''

    def __init__(self, screen_temp, x, y):
        self.x = x
        self.y = y
        moveing.__init__(self, self.x, self.y)

        self.screen = screen_temp
        self.image = pygame.image.load("./images/pd.png")

    def display(self):
        '''绘制子弹'''
        self.screen.blit(self.image, (self.x, self.y))


class Enemy_Bullt(moveing):
    '''敌机子弹类'''

    def __init__(self, screen_temp, x, y):
        self.x = x
        self.y = y
        self.hurt = False
        moveing.__init__(self, self.x, self.y)

        self.screen = screen_temp
        self.image = pygame.image.load("./images/pd.png")

    def display(self):
        '''绘制子弹'''
        self.screen.blit(self.image, (self.x, self.y))

    def move(self, hero):
        self.y += 8
        if self.y >= 568:
            return True

        if self.x > hero.x + 10 and self.x < hero.x + 92 and self.y > hero.y + 20 and self.y < hero.y + 60:
            self.hurt = True
            return True


def Key_control(hero_temp):
    '''键盘控制函数'''

    # 飞机的移动速度
    hero_speed = 5

    # 执行退出游戏操作
    for event in pygame.event.get():
        if event.type == QUIT:
            print('退出游戏')
            exit()

    # 获取按键信息
    press_keys = pygame.key.get_pressed()

    # 判断按键，执行对象的操作
    if press_keys[K_LEFT] or press_keys[K_a]:
        print('Left...')
        hero_temp.move_left_righe(-hero_speed)

    elif press_keys[K_RIGHT] or press_keys[K_d]:
        print('Right...')
        hero_temp.move_left_righe(hero_speed)

    if press_keys[K_SPACE]:
        print('Space...')
        hero_temp.fire()


def main():
    '''主程序函数'''
    # 创建游戏窗口
    screen = pygame.display.set_mode((512, 568), 0, 0)

    # 创建游戏背景
    background = pygame.image.load('./images/bg2.jpg')

    # 创建玩家飞机（英雄）
    hero = HeroPlane(screen)

    m = -968

    enemy_list = []  # 存放敌机的列表
    enemy_bullt_list = []
    game_over = True
    game_score = 0  # 游戏分数

    while game_over:
        # 绘制画面
        screen.blit(background, (0, m))
        m += 2
        if m >= -200:
            m = -968
        # 绘制玩家飞机
        hero.display()

        # 执行键盘控制
        Key_control(hero)

        # 随机绘制敌机
        if random.choice(range(50)) == 10:
            enemy_list.append(EnemyPlane(screen))

        # 遍历敌机并绘制移动
        for em in enemy_list:
            em.display()
            if em.bomb == 0:
                em.move(hero)
            elif em.bomb == 2:
                enemy_list.remove(em)
                game_score += 1

            # 刷新30次，发射一发子弹
            # 放在外面保证子弹不会随着飞机的消失而消失
            if em.time == 70:
                em.time = 0
                enemy_bullt_list.append(Enemy_Bullt(screen, em.x + 49, em.y + 80))

        # 绘制敌机子弹
        for b in enemy_bullt_list:
            b.display()
            if b.move(hero):
                if b.hurt:
                    print('中枪了，游戏结束，游戏分数为：{}'.format(game_score))
                    game_over = False
                enemy_bullt_list.remove(b)

        # 更新显示
        pygame.display.update()

        # 定时显示
        time.sleep(0.04)


if __name__ == '__main__':
    main()
